package com.hsy.crm.web.utils;

import com.google.common.collect.Lists;
import com.hsy.crm.web.domain.ex.UtilsException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import java.util.List;

public class ExcelUtils {

    public static <T> List<T> toList(Sheet sheet,String[] properties,int startRow,Class<T> tClass){
        List<T> data = Lists.newArrayList();

        int lastRowNum = sheet.getLastRowNum();

        for( int i=startRow ; i<=lastRowNum ; i++ ){
            Row row = sheet.getRow(i);
            if( row != null ){
                T t = newInstance(tClass);
                for( int j=0 ; j<properties.length ; j++ ){
                    Object cellValue = getCellValue(row.getCell(j));
                    if( cellValue != null && cellValue.toString().trim().length()>0 ){
                        PropertyUtils.setProperty(t,properties[j],cellValue);
                    }
                }
                data.add(t);
            }
        }
        return data;
    }

    private static Object getCellValue(Cell cell){
        if( cell == null ){
            return null;
        }
        if( cell.getCellType() == Cell.CELL_TYPE_STRING ){
            return cell.getStringCellValue();
        }else if( cell.getCellType() == Cell.CELL_TYPE_NUMERIC ){
            return cell.getNumericCellValue();
        }

        return null;
    }

    private static <T> T newInstance(Class<T> tClass){
        try {
            return tClass.newInstance();
        } catch (InstantiationException e) {
            throw new UtilsException(e);
        } catch (IllegalAccessException e) {
            throw new UtilsException(e);
        }
    }

}

